package cn.ucox.web.ms.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author chenw
 * @create 2017-05-12 18:14
 * @email javacspring@gmail.com
 */
public class SpringContext implements ApplicationContextAware {

    private static ApplicationContext sApplicationContext;

    public SpringContext() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        sApplicationContext = applicationContext;
    }

    public static ApplicationContext getContext() {
        return sApplicationContext;
    }

    public static <T> T getBean(String name) throws RuntimeException {
        assert null != name;

        Object obj = sApplicationContext.getBean(name);
        if (null == obj) {
            throw new RuntimeException("spring context cannot find bean with name " + name);
        } else {
            try {
                return (T) sApplicationContext.getBean(name);
            } catch (Exception var3) {
                throw new RuntimeException("spring bean class not match with " + name);
            }
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        return sApplicationContext.getBean(clazz);
    }
}
